package com.cll.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cll.constant.MessageConstant;
import com.cll.dto.UserLoginDTO;
import com.cll.entity.User;
import com.cll.exception.LoginFailedException;
import com.cll.mapper.UserMapper;
import com.cll.properties.WeChatProperties;
import com.cll.service.UserService;
import com.cll.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户实现类
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //1.获取openid
        String openId = getOpenId(userLoginDTO.getCode());

        //如果openId无效,结束程序
        if (openId == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //2.调用userMapper根据openId查询用户对象
        User user = userMapper.getByOpenId(openId);

        //3.判断用户User是否为null
        if (user == null){
            //如果为null，说明没有注册过程，进行自动注册（根据openid和创建时间插入用户表）
            user = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.save(user);
        }

        //4.返回登录用户对象  到了这里说明是已经注册过的,直接返回user进行登录
        return user;
    }

    @Autowired
    private WeChatProperties weChatProperties;
    //2.定义url  微信小程序登录的url
    @Autowired
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 根据授权码获取openId  openId是唯一确认登录人的信息
     * @param code
     * @return
     */
    private String getOpenId(String code){

        //1.创建Map封装4个参数数据
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");

        //3.使用工具类HttpClientUtil的doGet发送请求并返回json结果
        String json= HttpClientUtil.doGet(WX_LOGIN, map);

        //4.使用JSON.parseObject(json) 返回JSONObject
        JSONObject jsonObject = JSON.parseObject(json);

        //5.解析openid成字符串 返回
        return jsonObject.get("openid").toString();
    }

}
